module mvwnd ! moving window
    implicit none
    real(8), pointer, dimension(:,:,:) :: phi, J
    integer, private :: nq, dim1, dim2, ng
    integer, private :: last
contains

subroutine init_mvwnd(nq_, dim1_, dim2_, ng_)
    integer :: nq_, dim1_, dim2_, ng_
    
    nq=nq_;dim1=dim1_;dim2=dim2_;ng=ng_
    allocate (phi(dim1, ng, nq))
    allocate (J(dim2, ng, nq))
    phi = 0
    J = 0
end subroutine

subroutine add_mvwnd(nphi, nJ)
    real(8), pointer, intent(in), dimension(:,:) :: nphi, nJ
    call increase_mvwnd  
    phi(:,:,last) = nphi 
    J(:,:,last) = nJ
end subroutine

subroutine get_mvwnd(nphi, nJ)
    real(8), pointer, intent(out), dimension(:,:) :: nphi
    real(8), pointer, intent(out), dimension(:,:) :: nJ
    integer :: i
    nphi = 0
    nJ = 0
    do i=1, nq
        nphi = nphi + phi(:,:,i)
        nJ = nJ + J(:,:,i)
    end do
end subroutine

subroutine increase_mvwnd
    last = last +1
    if (last > nq) last = 1
endsubroutine
    

end module
